# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if root is None:
            return None
        
        if root == p or root == q:
            return root
        
        left_node = self.lowestCommonAncestor(root.left, p, q)
        right_node = self.lowestCommonAncestor(root.right, p, q)

        # 情况1：两个节点都存在
        if left_node and right_node:
            return root
        
        # 情况2：两个节点都不存在
        if left_node is None and right_node is None:
            return None

        # 情况3：只有一个节点存在，另一个不存在
        return left_node \
                if left_node and right_node is None \
                else \
                right_node